package com.taotao.search.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.taotao.common.pojo.EasyUIResult;
import com.taotao.search.pojo.Item;
@Service
public class SearchService {

	@Autowired
	private HttpSolrServer solrServer;

	public EasyUIResult query(String query, Integer page, Integer rows) {

		SolrQuery solrQuery = new SolrQuery();

		// 是否高亮
		Boolean isHighLighting = true;
		// 判断查询条件是否为空,如果为空,设置查询条件为*,并且不需要高亮
		if (StringUtils.isEmpty(query)) {
			// 查询所有商品
			query = "*";
			isHighLighting = false;
		}

		solrQuery.setQuery("title:" + query);

		// 设置分页
		solrQuery.setStart((page - 1) * rows);
		solrQuery.setRows(rows);

		// 设置高亮
		if (isHighLighting) {
			solrQuery.setHighlight(true);
			solrQuery.addHighlightField("title");
			solrQuery.setHighlightSimplePre("<em>");
			solrQuery.setHighlightSimplePost("</em>");
		}

		try {
			// 执行查询,获取结果集
			QueryResponse response = solrServer.query(solrQuery);
			// 获取普通结果集
			List<Item> list = response.getBeans(Item.class);
			// 获取高亮结果集
			if (!isHighLighting) {
				return new EasyUIResult<>(response.getResults().getNumFound(),list);
			}
				Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
				for (Item item : list) {
					Map<String, List<String>> map = highlighting.get(item.getId().toString());
					if (!CollectionUtils.isEmpty(map) && !CollectionUtils.isEmpty(map.get("title"))) {
						item.setTitle(map.get("title").get(0));
					}
				}
			
			// 查询总条数
			Long count = response.getResults().getNumFound();
			return new EasyUIResult<>(count, list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new EasyUIResult<>(0,new ArrayList<Item>());
	}

}
